import ResponsiveLayout from "@/components/ResponsiveLayout";
import Footer from "@/components/Footer";
import ProductTabs from "@/components/ProductTabs";
import { webAPI } from "@/lib/api";
import type { Product, ProductCategory } from "@/lib/api";
import Link from "next/link";
import ContactUs from "@/components/ContactUs";
import RecommendedProducts from "@/components/RecommendedProducts";
import Banner from "@/components/Banner";
import WeChatShareProvider from "@/components/WeChatShareProvider";

// 服务端获取产品分类数据
async function getProductCategories(): Promise<ProductCategory[]> {
  try {
    const response = await webAPI.getProductCategories();
    if (response.success) {
      return response.data;
    }
  } catch (error) {
    console.error("获取产品分类失败:", error);
  }
  return [];
}

// 服务端获取产品数据
async function getProducts(categoryId?: number): Promise<{ products: Product[]; totalPages: number }> {
  try {
    const response = await webAPI.getProducts({
      page: 1,
      pageSize: 10,
      categoryId,
      sort: "latest",
    });
    if (response.success) {
      return {
        products: response.data.products,
        totalPages: response.data.totalPages,
      };
    }
  } catch (error) {
    console.error("获取产品列表失败:", error);
  }
  return { products: [], totalPages: 1 };
}

export default async function Products({ searchParams }: { searchParams: Promise<{ category?: string }> }) {
  const resolvedSearchParams = await searchParams;
  const categoryId = resolvedSearchParams.category ? Number(resolvedSearchParams.category) : undefined;

  // 并行获取数据
  const [categories, { products: initialProducts, totalPages: initialTotalPages }] = await Promise.all([getProductCategories(), getProducts(categoryId)]);

  // 获取分类名称用于微信分享
  const categoryName = categoryId ? categories.find(cat => cat.id === categoryId)?.name || "" : "";

  // 生成结构化数据
  const structuredData = {
    "@context": "https://schema.org",
    "@type": "CollectionPage",
    name: "AI产品库",
    description: "AI产品库汇集最新的人工智能产品、工具和应用，帮助用户发现和了解各类AI解决方案",
    url: `${process.env.NEXT_PUBLIC_SITE_URL || "https://aiproducthome.com"}/products`,
    mainEntity: {
      "@type": "ItemList",
      itemListElement: initialProducts.map((product, index) => ({
        "@type": "ListItem",
        position: index + 1,
        item: {
          "@type": "SoftwareApplication",
          name: product.title,
          description: product.summary || product.content.substring(0, 200),
          applicationCategory: product.category?.name,
          operatingSystem: "Web",
          url: `${process.env.NEXT_PUBLIC_SITE_URL || "https://aiproducthome.com"}/products/${product.slug}`,
          author: {
            "@type": "Organization",
            name: product.author,
          },
        },
      })),
    },
    breadcrumb: {
      "@type": "BreadcrumbList",
      itemListElement: [
        {
          "@type": "ListItem",
          position: 1,
          name: "首页",
          item: `${process.env.NEXT_PUBLIC_SITE_URL || "https://aiproducthome.com"}`,
        },
        {
          "@type": "ListItem",
          position: 2,
          name: "产品",
          item: `${process.env.NEXT_PUBLIC_SITE_URL || "https://aiproducthome.com"}/products`,
        },
      ],
    },
  };

  return (
    <ResponsiveLayout active="products">
      {/* 结构化数据 */}
      <script
        type='application/ld+json'
        dangerouslySetInnerHTML={{
          __html: JSON.stringify(structuredData),
        }}
      />

      <WeChatShareProvider 
        title={categoryId ? `${categoryName}产品 - AI产品之家` : "AI产品之家-产品：学好AI产品，打开智能世界的大门"}
        description={categoryId ? `探索${categoryName}领域的最新AI产品，发现优质的人工智能工具和应用。` : "优选好用产品、简明产品概览、深度功能体验、一键直达应用。"}
        imageUrl="/banner/products_banner_pc.png"
      />

      {/* Banner */}
      <Banner pcImage='/banner/products_banner_pc.png' mobileImage='/banner/products_banner_mb.png' alt='AI产品库 - 发现最新的人工智能产品、工具和应用' />

      {/* Category Filters */}
      <nav className='container mx-auto max-w-6xl px-4 py-4' aria-label='产品分类导航'>
        <div className='space-y-2 flex'>
          {/* <span className="text-base font-bold text-gray-700 w-[50px] pr-2 pt-2">分类:</span> */}
          <div className='flex flex-wrap items-center gap-2'>
            <Link href='/products' className={`px-4 py-2 text-sm rounded-full border transition-all duration-200 ease-in-out transform hover:-translate-y-0.5 ${!categoryId ? "bg-blue-600 text-white border-blue-600 font-semibold shadow-sm" : "bg-white text-gray-700 border-gray-300 hover:bg-gray-100 hover:border-gray-400 font-medium"}`} aria-current={!categoryId ? "page" : undefined}>
              全部
            </Link>
            {categories.map(category => (
              <Link key={category.id} href={`/products?category=${category.id}`} className={`px-4 py-2 text-sm rounded-full border transition-all duration-200 ease-in-out transform hover:-translate-y-0.5 ${categoryId === category.id ? "bg-blue-600 text-white border-blue-600 font-semibold" : "bg-white text-gray-700 border-gray-300 hover:bg-gray-100 hover:border-gray-400 font-medium"}`} aria-current={categoryId === category.id ? "page" : undefined}>
                {category.name}
              </Link>
            ))}
          </div>
        </div>
      </nav>

      {/* Main Content */}
      <div className='container mx-auto max-w-6xl px-4 pb-8'>
        <div className='grid grid-cols-1 lg:grid-cols-3 gap-8'>
          <div className='lg:col-span-2'>
            <ProductTabs initialProducts={initialProducts} initialTotalPages={initialTotalPages} categoryId={categoryId} />
          </div>

          {/* Right Sidebar */}
          <aside className='lg:col-span-1 space-y-8'>
            <RecommendedProducts pageSize={10} title='推荐产品' showMoreLink={false} />
            <ContactUs />
          </aside>
        </div>
      </div>
      <Footer />
    </ResponsiveLayout>
  );
}
